import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

///==============================================================================================================
///BasicMessageChannel用法
final BasicMessageChannel<String> basicMessageChannel = BasicMessageChannel("com.test.basic", StringCodec());

/// 发送BasicMessage
void sendBasicMessage(String msg) {
  basicMessageChannel.send(msg);
}

/// 接收BasicMessage消息
void setUpReceiveMessage(Function(dynamic content) callBackContent) {
  basicMessageChannel.setMessageHandler((dynamic message) async {
    // 处理收到的消息
    print('Received message: $message');
    callBackContent(message);
    return 'Received!';
  });
}

///==============================================================================================================
///EventChanel 用法
final EventChannel eventChannel = EventChannel('com.test.event/channel');
// 监听来自原生平台的数据流
void listenToNativeStream(Function(dynamic content) eventCallBack) {
  eventChannel.receiveBroadcastStream().listen((dynamic event) {
    // 处理原生平台发来的数据
    print('Received event: $event');
    eventCallBack("${event}");

  }, onError: (dynamic error) {
    // 处理错误
    print('Received error: ${error.message}');
  });
}

///=============================
///MethodChannel 用法
const nativeMethod = MethodChannel('com.test.method');
void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Android 通信Demo1',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Android 通信Demo2'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  dynamic nativeCallBackMessage = "";
  dynamic nativeCallBackEvent = "";
  dynamic methtodResult="";

  @override
  void initState() {
    super.initState();
    setUpReceiveMessage((content) {
      nativeCallBackMessage = content;
      setState(() {});
    });

    listenToNativeStream((content) {
      nativeCallBackEvent=content;
      setState(() {});
    });



  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[

            Text("最新的Basic Message Channel反馈:${nativeCallBackMessage}"),
            Text("最新的Event Channel反馈:${nativeCallBackEvent}"),
            Text("最新的Method Channel反馈:${methtodResult}"),

            TextButton(
                onPressed: () {
                  sendBasicMessage("Send Basic mesg--> ${DateTime.now()}");
                },
                child: Text("BasicMessageChannel 通信测试")
            ),

            TextButton(
                onPressed: () async {
                  var res= await nativeMethod.invokeMethod("test","Hello I am argument");
                  methtodResult=res;
                  setState(() {

                  });
                },
                child: Text("MethodChannel 通信")
            ),

          ],
        ),
      ),
      // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}
